<?php defined('SYSPATH') or die('No direct script access.');
 
class html extends html_Core {

    public static function createCrudPath($entityName, $entity, $indentifyingField, $pkField, $listMethod='all') {
    	$siteSpace = Router::$segments[0];
        $path = array($entityName . '.form-title' => '/' . $siteSpace . '/' . $entityName . '/' . $listMethod);
        if (sql::isPersistent($entity)) {
            $objectName = '';
            if (is_array($indentifyingField)) {
                foreach ($indentifyingField as $field) {
                    $objectName .= $entity[$field] . ' ';
                }
                $objectName = trim($objectName);
            }
            else {
                $objectName = $entity[$indentifyingField];
            }
            $path[$objectName] = '/' . $siteSpace . '/' . $entityName . '/display?' . $pkField . '=' . $entity[$pkField];
            $path['application.page-title-edit'] = '';
        }
        else {
            $path['application.page-title-insert'] = '';
        }
        return $path;
    }

    /**
     * Prints path.
     */
    public static function printPath($path, $description=null) {
        if (! is_array($path)) {
            $path = array($path => '');
        }
        
        $headerHtml = '<div class="header">';
        $delimiter = '&raquo;';
        $index = 0;
        $popupItemClass = '';
        foreach ($path as $labelKey => $url) {
            if ($index == 0) {
                $headerHtml .= '<ol class="breadcrumbs">';
                $popupTitle = '<ol class="breadcrumbs">';
            }

            $label = self::labelValue($labelKey);

            if ($index == count($path) - 1) {
                $headerHtml .= '</ol>';
                $headerHtml .= '<h1>' . $label . '</h1>';
                $popupItemClass = 'lastItem';
            }
            else {
                $headerHtml .= '<li>';
                $altActions = NULL;
                if (is_array($url)) {
                    $altActions = $url;
                    $url = $url[0];
                    unset($altActions[0]);
                }
                if ($url != '') {
                $headerHtml .= HTML::anchor($url, $label);
                }
                else {
                    $headerHtml .= $label;
                }
                if ($altActions) {
                    $headerHtml .= '<ol>';
                    foreach ($altActions as $altLabel => $altUrl) {
                        $headerHtml .= '<li>' . HTML::anchor($altUrl, self::labelValue($altLabel)) . '</li>';
                    }
                    $headerHtml .= '</ol>';
                }
                $headerHtml .= '</li>';
            }

            $popupTitle .= '<li class="' . $popupItemClass . '">' . $label . '</li>';
            $index++;
        }
        $popupTitle .= '</ol>';

        if ($description) {
            $headerHtml .= '<p class="description">' . text::get($description) . '</p>';
        }

        $headerHtml .= '</div>';
        if (request::isPopup()) {
            if ($description) {
                echo '<div class="header"><p class="description">' . text::getEscaped($description) . '</p></div>';
            }
            echo '<span class="popupTitle">' . $popupTitle . '</span>';
        }
        else {
            echo $headerHtml;
        }
    }

    private static function labelValue($labelKey) {
        // If the label key matches the expected pattern, it is really a l10n key.
        // Otherwise, it is just a value.
        if (preg_match('/[a-zA-Z0-9-_]+\\.[a-zA-Z0-9-_]+/', $labelKey)) {
            $label = text::get($labelKey);
        }
        else {
            $label = $labelKey;
        }
        return $label;
    }

    public static function listHeader($field, $entityName, $sortOrder, $tableName, $titleKey=null) {
        echo '<th';
        if ($field != null) {
            $onclick = ' onclick="orderList(\'' . $tableName . '\', \'' . $field . "'";
            if ($sortOrder) {
                if ($sortOrder->field == $field && $sortOrder->direction == 'ASC') {
                    $onclick .= ", 'DESC'";
                }
            }
            $onclick .= ');"';
            echo $onclick;
        }
        echo '>';

        if ($sortOrder) {
            if ($sortOrder->field == $field) {
                $img = 'order';
                if ($sortOrder->direction == 'ASC') {
                    $img .= 'Desc';
                }
                else {
                    $img .= 'Asc';
                }
                $img .= '.png';
                echo html::img($img, array('class' => 'orderImage'));
            }
        }
        if ($titleKey == null) {
            $titleKey = $entityName . '.' . $field;
        }
        echo text::getEscaped($titleKey);
        echo '</th>';
    }
    
    public static function textField($entityName, $fieldName) {
        $html = '<tr>';
        $html .= '<th><label for="' . $fieldName . '">' . text::get($entityName . '.' . $fieldName) . '</label></th>';
        $html .= '<td><input type="text" id="' . $fieldName . '" name="' . $fieldName . '" value="' . $entityName[$fieldName] . '" /></td>';
        $html .= '</tr>';
        return $html;
    }

    private static function themedFilePath($dir, $file) {
        $theme = Kohana::config('yosemin.theme');
        if (is_file($_SERVER['DOCUMENT_ROOT'] . url::base(FALSE) . 'themes/' . $theme . '/' . $dir . '/' . $file)) {
            $path = url::base(FALSE) . 'themes/' . $theme . '/' . $dir . '/' . $file;
        }
        else {
            $path = url::base(FALSE) . 'themes/default/' . $dir . '/' . $file;
        }
        return $path;
    }

    public static function img($src, $attributes = array()) {
        $attributes['src'] = self::themedFilePath('images', $src);
        return '<img' . html::attributes($attributes) . ' />';
    }

    public static function css($src, $themed = TRUE) {
        if ($themed) {
            $src = self::themedFilePath('css', $src);
        }
        else {
            $src = url::base(FALSE) . $src;
        }

        return '<link rel="stylesheet" href="' . $src . '" />';
    }

    public static function javascript($src) {
        // $src = self::themedFilePath('javascript', $src);
        $src = url::base(FALSE) . $src;
        return '<script type="text/javascript" src="' . $src . '"></script>';
    }

    public static function popup($url, $text, $extraAttrs=NULL) {
        $attrs = array (
            'onclick' => "return Yosemin.Popup.open('" . url::site($url) . "', event);",
            'class' => 'popupAnchor'
        );
        if ($extraAttrs) {
            $attrs = array_merge($attrs, $extraAttrs);
        }
        return html::anchor('#', $text, $attrs);
    }

    public static function moreInfoPopup($url, $text) {
        return self::popup($url, $text, array('title' => text::get('application.moreInfoAnchorTitle')));
    }

    public static function searchEntityAnchor($controller) {
        $controllerUrl = '/admin/' . $controller->entityName;
        $html = html::anchor('',
                text::get('application.findRecordsByCriteria'),
                array('onclick' => "return Yosemin.Popup.open('" . url::site($controllerUrl . '/searchForm') . "', event);"));
        if ($controller->hasSearchCriteria()) {
            $html .= '<ul><li>' . html::anchor($controllerUrl . '/clearSearchCriteria', text::get('application.queryAllRecords')) . '</li></ul>';
        }
        return $html;
    }

    public static function popupForm($url, $text, $attributes=NULL) {
        $onclick = "new Dialog('" . url::site($url) . "', null, true).open(); return false;";
        if (! is_array($attributes)) {
            $attributes = array();
        }
        $attributes = array_merge(array('onclick' => $onclick), $attributes);
        return html::anchor('#', $text, $attributes);
    }

    /**
     * @return String class name for the collapsable block controlled by this header.
     */
    public static function printCollapsableBlockHeader($labelKey, $visibleByDefault, $propertyKey=NULL, $blockId=NULL) {
        if ($propertyKey) {
            $paymentsVisible = SessionData::instance()->getProperty($propertyKey);
        }
        if ($paymentsVisible === NULL) {
            $paymentsVisible = $visibleByDefault;
        }
        $toggleIcon = 'toggle-plus.png';
        $toggledBlockClass = 'hidden';
        if ($paymentsVisible) {
            $toggleIcon = 'toggle-minus.png';
            $toggledBlockClass = '';
        }

        // Construct onclick JavaScript call
        if ($propertyKey) {
            $onclick = "toggleBlockByHeader(this, '" . $propertyKey . "', ";
        }
        else {
            $onclick = "toggleBlockByHeader(this, null, ";
        }
        if ($blockId) {
            $onclick .= "'" . $blockId . "')";
        }
        else {
            $onclick .= "null)";
        }

        echo '<h2 class="collapsableBlockHeader"><span onclick="' . $onclick . '">' . html::img($toggleIcon) . text::getEscaped($labelKey) . '</span></h2>';
        if ($paymentsVisible) {
            return '';
        }
        return 'hidden';
    }

    public static function entityInfoIcon($entityName, $entity, $pkField) {
        $pkValue = $entity[$pkField];
        return html::popup('/admin/adminSpace/entityInfo?entityName=' . $entityName . '&pkField=' . $pkField . '&pkValue=' . $pkValue,
                html::img('action/entityInfo.png'),
                array(
                    'class' => 'entityInfo',
                    'title' => text::get('application.entityInfo')
                ));
    }

    public static function slideToggle($label, $elementId, $title=NULL) {
        $params = array(
            'onclick' => "$('#" . $elementId . "').slideToggle('fast'); return false;"
        );
        if ($title) {
            $params['title'] = $title;
        }
        return html::anchor('#', $label, $params);
    }
    
    public static function escape($text) {
        if (is_array($text)) {
            return $text;
        }
        return htmlspecialchars($text);
    }
    
    public static function displayTable($valueMap, $skipEmpty = true, $escapeLabelHtml = TRUE, $escapeValueHtml = TRUE) {
        if ($skipEmpty) {
            $trimmedMap = array();
            foreach ($valueMap as $label => $value) {
                if (! empty($value)) {
                    $trimmedMap[$label] = $value;
                }
            }
        }
        else {
            $trimmedMap = $valueMap;
        }
        
        if (count($trimmedMap) > 0) {
            echo '<table class="displayTable">';
            echo '<tbody>';
            foreach ($trimmedMap as $label => $value) {
            	if ($escapeLabelHtml) {
            		$label = html::escape($label);
            	}
            	if ($escapeValueHtml) {
            		$value = html::escape($value);
            	}
                echo '<tr><th>' . $label . '</th><td>' . $value . '</td></tr>';
            }
            echo '</tbody>';
            echo '</table>';
        }
    }
    
    public static function wrapInHtml($text, $title='') {
    	return '<!doctype html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>' .
    			$title . '</title></head><body>' . 
    			$text . '</body></html>';
    }
    
    public static function inlineJavaScript($script) {
    	return '<script type="text/javascript">' . $script . '</script>';
    }
    
    public static function crossroads($currentSpace) {
    	$sessionData = SessionData::instance();
    	$user = $sessionData->getAuthUser();
    	$crossroadsLinks = array();
    	
    	// Link to the user space
    	$crossroadsLinks['user'] = html::anchor('/user/seminarChoice', text::get('admin.menu-goToUserSpace'));
    	
    	// Link to the admin space
    	if ($user['is_admin']) {
    		$crossroadsLinks['admin'] = html::anchor('/admin/adminSpace', text::get('userSpace-menu-goToAdminSpace'));
    	}
    	// Link to the organization space
    	$authOrg = $sessionData->getAuthOrg();
    	if ($authOrg) {
    		$crossroadsLinks['org'] = html::anchor('/org/orgSpace/welcome', text::get('userSpace-menu-organization'), array('title' => $authOrg['name']));
    	}
    	else {
    		$organizerList = $user['organizerList'];
    		$representativeList = $user['representativeList'];
    		if ($organizerList || $representativeList) {
    			$crossroadsLinks['org'] = html::anchor('/user/userSpace/welcome', text::get('userSpace-menu-organization'));
    		}
    	}
    	
    	// Link to the reception desk
    	if ($user['receptionSeminar']) {
    		// TODO: Reception is not needed yet
    		// $crossroadsLinks['reception'] = html::anchor('/reception/receptionSpace', text::get('userSpace-menu-goToReception'));
    	}
    	
    	// If the user cannot go anywhere else except current space, don't show the crossroads
    	if (count($crossroadsLinks) > 1) {
	    	echo '<div class="crossroads">' . html::img('crossroads2.png');
	    	echo '<ul>';
	    	foreach ($crossroadsLinks as $space => $link) {
	    		echo '<li class="' . ($space == $currentSpace ? 'currentSpace' : '') . '">' . $link . '</li>';
	    	}
	    	echo '</ul></div>';
    	}
    }
    
    public static function actionLists($model) {
    	echo '<div class="commandListFlow ui-helper-clearfix">';
    	echo '<ul class="commandList">';
    	foreach ($model as $key => $section) {
    		if (! is_array($section)) {
    			$section = array($key => $section);
    		}
    		foreach ($section as $className => $link) {
    			echo '<li class="' . $className . '">' . $link . '</li>';
    		}
    	}
    	echo '</ul>';
    	echo '</div>';
    }
}